// 基于 axios 封装的请求模块
import axios from 'axios'
import store from '../store'
import router from '../router'
import { updataToken } from '@/api/user.js'

// 相应拦截器
axios.interceptors.response.use(function (response) {
  return response.data
}, async function (error) {
  // console.dir(error)
  if (error.response.data.message === 'refresh_token失效') {
    router.push({
      path: '/login?from=' + router.currentRoute.fullPath
    })
  }
  if (error.response.status === 401) {
    store.commit('setToken', '')
    const resp = await updataToken()
    console.log(resp)
    store.commit('setToken', resp.data.token)
    return axios(error.config)
  }
  return Promise.reject(error)
})

// 请求拦截器
axios.interceptors.request.use(function (config) {
  config.baseURL = 'http://toutiao.itheima.net'
  if (store.state.token) { config.headers.Authorization = 'Bearer ' + store.state.token } else {
    config.headers.Authorization = 'Bearer ' + store.state.refresh_token
  }

  return config
}, function (error) {
  return Promise.reject(error)
})
// 导出自定义函数
export default axios
